<template>
  <div class="roles-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>角色管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>

      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索角色名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-table
        :data="filteredRoles"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="用户数" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" @click="showPermissionDialog(row)">权限</el-button>
            <el-button size="small" @click="showUserDialog(row)">用户</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRole" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="500px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedPermissions"
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="savingPermissions">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户分配对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="分配用户"
      width="600px"
    >
      <div class="user-assignment">
        <div class="user-list">
          <h4>可选用户</h4>
          <el-table
            :data="availableUsers"
            style="width: 100%"
            height="300"
          >
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="realName" label="真实姓名" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" @click="assignUser(row)">分配</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="user-list">
          <h4>已分配用户</h4>
          <el-table
            :data="assignedUsers"
            style="width: 100%"
            height="300"
          >
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="realName" label="真实姓名" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="removeUser(row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="userDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleApi } from '@/api/role'

export default {
  name: 'Roles',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const savingPermissions = ref(false)
    const roles = ref([])
    const permissionTree = ref([])
    const availableUsers = ref([])
    const assignedUsers = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const roleDialogVisible = ref(false)
    const permissionDialogVisible = ref(false)
    const userDialogVisible = ref(false)
    const isEdit = ref(false)
    const currentRole = ref(null)
    const selectedPermissions = ref([])

    const roleForm = reactive({
      name: '',
      description: '',
      status: 'active'
    })

    const roleRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' }
      ]
    }

    const treeProps = {
      children: 'children',
      label: 'name'
    }

    const filteredRoles = computed(() => {
      if (!searchKeyword.value) return roles.value
      return roles.value.filter(role => 
        role.name.includes(searchKeyword.value) ||
        role.description.includes(searchKeyword.value)
      )
    })

    const loadRoles = async () => {
      loading.value = true
      try {
        // 模拟API调用
        const mockRoles = [
          {
            id: 1,
            name: '管理员',
            description: '系统管理员，拥有所有权限',
            status: 'active',
            userCount: 2,
            createTime: '2024-01-01 10:00:00'
          },
          {
            id: 2,
            name: '教师',
            description: '教师角色，可以管理学生信息',
            status: 'active',
            userCount: 5,
            createTime: '2024-01-02 10:00:00'
          },
          {
            id: 3,
            name: '学生',
            description: '学生角色，只能查看自己的信息',
            status: 'active',
            userCount: 150,
            createTime: '2024-01-03 10:00:00'
          }
        ]
        roles.value = mockRoles
        total.value = mockRoles.length
      } catch (error) {
        ElMessage.error('加载角色列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadPermissionTree = async () => {
      try {
        // 模拟权限树数据
        permissionTree.value = [
          {
            id: 1,
            name: '系统管理',
            children: [
              { id: 11, name: '用户管理' },
              { id: 12, name: '角色管理' },
              { id: 13, name: '权限管理' }
            ]
          },
          {
            id: 2,
            name: '教务管理',
            children: [
              { id: 21, name: '课程管理' },
              { id: 22, name: '成绩管理' },
              { id: 23, name: '班级管理' }
            ]
          }
        ]
      } catch (error) {
        ElMessage.error('加载权限树失败')
      }
    }

    const loadUsers = async () => {
      try {
        // 模拟用户数据
        availableUsers.value = [
          { id: 1, username: 'teacher1', realName: '张老师' },
          { id: 2, username: 'teacher2', realName: '李老师' }
        ]
        assignedUsers.value = [
          { id: 3, username: 'admin', realName: '管理员' }
        ]
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      }
    }

    const showAddDialog = () => {
      isEdit.value = false
      Object.assign(roleForm, {
        name: '',
        description: '',
        status: 'active'
      })
      roleDialogVisible.value = true
    }

    const showEditDialog = (role) => {
      isEdit.value = true
      currentRole.value = role
      Object.assign(roleForm, {
        name: role.name,
        description: role.description,
        status: role.status
      })
      roleDialogVisible.value = true
    }

    const showPermissionDialog = (role) => {
      currentRole.value = role
      selectedPermissions.value = [11, 12] // 模拟已选权限
      permissionDialogVisible.value = true
    }

    const showUserDialog = (role) => {
      currentRole.value = role
      loadUsers()
      userDialogVisible.value = true
    }

    const handleSaveRole = async () => {
      try {
        await roleFormRef.value.validate()
        saving.value = true
        
        if (isEdit.value) {
          ElMessage.success('角色更新成功')
        } else {
          ElMessage.success('角色创建成功')
        }
        
        roleDialogVisible.value = false
        loadRoles()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }

    const handleSavePermissions = async () => {
      try {
        savingPermissions.value = true
        const checkedKeys = permissionTreeRef.value.getCheckedKeys()
        ElMessage.success('权限分配成功')
        permissionDialogVisible.value = false
      } catch (error) {
        ElMessage.error('权限分配失败')
      } finally {
        savingPermissions.value = false
      }
    }

    const assignUser = (user) => {
      assignedUsers.value.push(user)
      availableUsers.value = availableUsers.value.filter(u => u.id !== user.id)
      ElMessage.success('用户分配成功')
    }

    const removeUser = (user) => {
      availableUsers.value.push(user)
      assignedUsers.value = assignedUsers.value.filter(u => u.id !== user.id)
      ElMessage.success('用户移除成功')
    }

    const handleDelete = async (role) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除角色 "${role.name}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('角色删除成功')
        loadRoles()
      } catch {
        // 用户取消
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadRoles()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadRoles()
    }

    onMounted(() => {
      loadRoles()
      loadPermissionTree()
    })

    return {
      loading,
      saving,
      savingPermissions,
      roles,
      permissionTree,
      availableUsers,
      assignedUsers,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      roleDialogVisible,
      permissionDialogVisible,
      userDialogVisible,
      isEdit,
      currentRole,
      selectedPermissions,
      roleForm,
      roleRules,
      treeProps,
      filteredRoles,
      showAddDialog,
      showEditDialog,
      showPermissionDialog,
      showUserDialog,
      handleSaveRole,
      handleSavePermissions,
      assignUser,
      removeUser,
      handleDelete,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.roles-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.user-assignment {
  display: flex;
  gap: 20px;
}

.user-list {
  flex: 1;
}

.user-list h4 {
  margin-bottom: 10px;
  color: #333;
}
</style> 